<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Cities;
use App\Models\FileUpload;
use App\Models\FilmTypeMaster;
use App\Models\MacroManagement;
use App\Models\MakeMaster;
use App\Models\ModelMaster;
use App\Models\PartMaster;
use App\Models\ProvinceMaster;
use App\Models\RegionMaster;
use App\Models\Roles;
use App\Models\Permissions;
use App\Models\RollMaster;
use App\Models\RollRestlen;
use App\Models\Users;
use App\Services\ModuleService;
use App\Services\RollsService;
use App\Services\UserService;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\IOFactory;
use App\Models\ProductTypes;
use Illuminate\Support\Facades\App;

/*
 * 卷膜管理*/
class RollsController extends Controller
{
    private $rollService;

    public function __construct(RollsService $rollsService)
    {
        $this->rollService = $rollsService;
    }

    protected function gly_index(Request $request)
    {
        $model = DB::table('roll_master as rm')
            ->leftJoin('roll_restlen as rr', 'rr.roll_number', 'rm.roll_number', function ($query) {
                $query->whereNull('rr.deleted_at');
            })
            ->whereNull('rm.deleted_at')
            ->where('rr.user_id', 1);
        $model = filterByDateRange($model, 'rm.created_at');
        /*$allocated = (int) $request->input('allocated');
        if ($allocated == 1) {
            $model->where('rm.length', '!=', DB::raw('rr.restlen'));
        } elseif ($allocated == 2) {
            $model->where('rm.length', DB::raw('rr.restlen'));
        } elseif ($allocated == 3) {
            $rts = DB::table('roll_restlen')
                ->whereNull('deleted_at')
                ->groupBy('roll_number')
                ->select([DB::raw('sum(restlen) as length'), 'roll_number']);
            $model = $model->leftJoinSub($rts, 'rts', 'rm.roll_number', 'rts.roll_number')
                ->where('rr.restlen', '!=', DB::raw('rts.length'))
                ->where('rm.length', DB::raw('rts.length'));
        }*/

        $product_type_id = (int) $request->input('product_type_id');
        $film_type_id = (int) $request->input('film_type_id');
        if (!empty($film_type_id)) {
            $model = $model->where('rm.film_type_id', $film_type_id);
        } else if (!empty($product_type_id)) {
            $model = $model->leftJoin('film_type_master as ftmm', 'rm.film_type_id', 'ftmm.id')
                ->where('ftmm.product_type_id', $product_type_id);
        }

        $status = $request->input('status');
        if ($status !== null) {
            $model = $model->where('rm.status', $status);
        }

        $distributor_id = (int) $request->input('distributor_id');
        $dealer_id = (int) $request->input('dealer_id');
        if (!empty($dealer_id)) {
            $model = $model->leftJoin('warranty_to_vehicle_coverage as wvc', 'rm.roll_number', 'wvc.roll_number')
                ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
                ->leftJoin('precut_to_vehicle_coverage as pvc', 'rm.roll_number', 'pvc.roll_number')
                ->leftJoin('precut as p', 'p.id', 'pvc.precut_kit_sale_id')
                ->where(function ($query) use ($dealer_id) {
                    $query->where(function ($q2) use ($dealer_id) {
                        $q2->where('rr.user_id', $dealer_id)
                            ->where('rr.restlen', '>', 0);
                    })
                        ->orWhere(function ($query) use ($dealer_id) {
                            $query->where('w.user_id', $dealer_id)
                                ->where('w.approved', 1)
                                ->whereNotNull('wvc.warranty_id')
                                ->whereNull('w.deleted_at')
                                ->whereNull('wvc.deleted_at');
                        })
                        ->orWhere(function ($query) use ($dealer_id) {
                            $query->where('p.created_by', $dealer_id)
                                ->whereNotNull('p.id')
                                ->whereNull('p.deleted_at')
                                ->whereNull('pvc.deleted_at');
                        });
                });

            /*$model = $model->leftJoin('roll_restlen as rd', 'rd.roll_number', 'rr.roll_number')
                ->where('rd.user_id', $dealer_id);*/
        } else if (!empty($distributor_id)) {
            $model = $model->leftJoin('warranty_to_vehicle_coverage as wvc', 'rm.roll_number', 'wvc.roll_number')
                ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
                ->leftJoin('precut_to_vehicle_coverage as pvc', 'rm.roll_number', 'pvc.roll_number')
                ->leftJoin('precut as p', 'p.id', 'pvc.precut_kit_sale_id')
                ->where(function ($query) use ($distributor_id) {
                    $query->where(function ($q2) use ($distributor_id) {
                        $q2->whereIn('rr.user_id', function ($query) use ($distributor_id) {
                            $query->select('id')
                                ->from('users')
                                ->where('id', $distributor_id)
                                ->orWhere('creator_id', $distributor_id);
                        })
                            ->where('rr.restlen', '>', 0);
                    })
                        ->orWhere(function ($query) use ($distributor_id) {
                            $query->whereIn('w.user_id', function ($query) use ($distributor_id) {
                                $query->select('id')
                                    ->from('users')
                                    ->where('id', $distributor_id)
                                    ->orWhere('creator_id', $distributor_id);
                            })
                                ->whereNotNull('wvc.warranty_id')
                                ->whereNull('w.deleted_at')
                                ->whereNull('wvc.deleted_at');
                        })

                        ->orWhere(function ($query) use ($distributor_id) {
                            $query->whereIn('p.created_by', function ($query) use ($distributor_id) {
                                $query->select('id')
                                    ->from('users')
                                    ->where('id', $distributor_id)
                                    ->orWhere('creator_id', $distributor_id);
                            })
                                ->whereNotNull('p.id')
                                ->whereNull('p.deleted_at')
                                ->whereNull('pvc.deleted_at');
                        });
                });
            /*$model = $model->->where('rr.user_id', $distributor_id);*/
        }

        // $select = ['rm.*', 'roll_sales.roll_id as roll_sales_id'];
        $select = ['rm.*', 'rr.restlen'];
        $model = $model->select($select)
            ->groupBy('rm.id');
        $model = $this->filterRolls($request, $model);
        $data = $model->orderByDesc('rm.id')->paginate(50);
        return $data;
    }

    protected function gly_index2(Request $request)
    {
        $model = DB::table('roll_master as rm')
            ->whereNull('rm.deleted_at')
            ->leftJoin('roll_sales', 'rm.id', '=', 'roll_sales.roll_id');
        $model = filterByDateRange($model, 'rm.created_at');
        $allocated = (int) $request->input('allocated');
        if ($allocated == 1) {
            $model->whereNotNull('roll_sales.roll_id');
        } elseif ($allocated == 2) {
            $model->whereNull('roll_sales.roll_id');
        }
        $select = ['rm.*', 'roll_sales.roll_id as roll_sales_id'];
        $model = $model->select($select)
            ->groupBy('rm.id');
        $model = $this->filterRolls($request, $model);
        $data = $model->orderByDesc('rm.id')->paginate(50);
        return $data;
    }

    protected function sd_index(Request $request)
    {
        $user_id = session()->get('admin.id');
        $rt = DB::table('roll_sales')
            ->where('sold_by_user_id', $user_id)
            ->whereNull('deleted_at')
            ->orderByDesc('id')
            ->groupBy('roll_id')
            ->select(['roll_id', 'type']);
        $rts = DB::table($rt)
            ->where('type', 3)
            ->get('roll_id');
        $ids = Arr::pluck($rts, 'roll_id');

        $status = $request->get('status') ?? null;

        $model = DB::table('roll_master as rm')
            ->leftJoin('roll_restlen as rr', 'rm.roll_number', 'rr.roll_number')
            ->leftJoin('roll_sales as rs', 'rm.id', 'rs.roll_id')
            ->whereNull('rr.deleted_at');
        if (strcmp($status, '0') === 0) {
            $model->where('rr.restlen', '>', 0)->where('rr.user_id', $user_id);
        }
        if (strcmp($status, '2') === 0) {
            $model->where('rr.restlen', 0)->where('rr.user_id', $user_id);
        }

        $model = $model->whereIn('rr.user_id', function ($query) use ($user_id) {
                $query->select('id')
                    ->from('users')
                    ->where('id', $user_id)
                    ->orWhere('creator_id', $user_id);
            })
            ->whereNull('rm.deleted_at')
            ->groupBy('rm.id');
            //->whereNotIn('rm.id', $ids)
        $model = filterByDateRange($model, 'rs.created_at');

        $product_type_id = (int) $request->input('product_type_id');
        $film_type_id = (int) $request->input('film_type_id');
        if (!empty($film_type_id)) {
            $model = $model->where('rm.film_type_id', $film_type_id);
        } else if (!empty($product_type_id)) {
            $model = $model->leftJoin('film_type_master as ftmm', 'rm.film_type_id', 'ftmm.id')
                ->where('ftmm.product_type_id', $product_type_id);
        }

        $dealer_id = (int) $request->input('dealer_id');
        if (!empty($dealer_id)) {
            $model = $model->where('rs.sold_to_user_id', $dealer_id);
        }
        $model = $this->filterRolls($request, $model);
        $model = $model->select('rm.*', 'rs.created_at as rs_created_at');
        $data = $model
            ->orderByDesc('rs.created_at')
            ->paginate(50);

        return $data;
    }

    protected function sd_index3(Request $request)
    {
        $user_id = session()->get('admin.id');
        $rt = DB::table('roll_sales')
            ->where('sold_by_user_id', $user_id)
            ->whereNull('deleted_at')
            ->orderByDesc('id')
            ->groupBy('roll_id')
            ->select(['roll_id', 'type']);
        $rts = DB::table($rt)
            ->where('type', 3)
            ->get('roll_id');
        $ids = Arr::pluck($rts, 'roll_id');


        $model = DB::table('roll_master as rm')
            ->leftJoin('roll_sales as rs', 'rm.id', 'rs.roll_id')
            ->whereIn('rs.sold_to_user_id', function ($query) use ($user_id) {
                $query->select('id')->from('users')->where('id', $user_id)
                    ->orWhere('creator_id', $user_id);
            })
            ->whereNull('rm.deleted_at')
            ->whereNotIn('rm.id', $ids)
            ->groupBy('rm.id');
        // ->where('rss.sold_by_user_id', function ($query) use ($user_id) {
        //                $query->select('id')->from('users')->where('id', $user_id)
        //                    ->orWhere('creator_id', $user_id);
        //            })
        $model = filterByDateRange($model, 'rm.created_at');
        $model = $this->filterRolls($request, $model);
        $model = $model->select('rm.*');
        $data = $model->paginate(50);

        return $data;
    }
    protected function sd_index2(Request $request)
    {
        $user_id = session()->get('admin.id');
        $model = DB::table('roll_master as rm')
            ->leftJoin('roll_sales as rs', 'rm.id', 'rs.roll_id')
            ->whereIn('rs.sold_to_user_id', function ($query) use ($user_id) {
                $query->select('id')->from('users')->where('id', $user_id)
                    ->orWhere('creator_id', $user_id);
            })
            ->whereNull('rm.deleted_at')
            ->groupBy('rm.id');
        // ->where('rss.sold_by_user_id', function ($query) use ($user_id) {
        //                $query->select('id')->from('users')->where('id', $user_id)
        //                    ->orWhere('creator_id', $user_id);
        //            })
        $model = filterByDateRange($model, 'rm.created_at');
        $model = $this->filterRolls($request, $model);
        $model = $model->select('rm.*');
        $data = $model->paginate(50);

        return $data;
    }

    // 产品管理-膜卷管理
    public function index(Request $request)
    {
        $user_id = session()->get('admin.id');
        $user_type = session()->get('admin.user_type');
        $page = [
            'page_name' => 'rolls',
            'title' => ts('MANAGEROLL'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEPRODUCT'),
                    'url' => 'javascript:void(0)'
                ]
            ],
        ];
        $menus = (new ModuleService())->getWebButton(session('admin.role_id') ?? 0, $request->path());

        if ($user_type == 2) {
            $data = $this->sd_index($request);
            $products = ProductTypes::orderBy('id')->get('id');
            return view('admin.rolls.sd-index', [
                'data'=>$data,
                'page' => $page,
                'menus' => $menus,
                'products' => $products,
            ]);
        } else {
            $role_opt = false;
            if ($user_type > 3) {
                checkAuthority();
                $role_opt = true;
                $user_id = 1;
            }
            if ($user_type == 1) {
                $user_id = 1;
            }
            if($user_type == 4) {
                $data = $this->rollService->getRolls($request);
            } else {
                $data = $this->rollService->getAdminRolls($request);
            }
            return view('admin.rolls.gly-index', [
                'data'=>$data,
                'page' => $page,
                'menus' => $menus,
            ]);
        }
    }

    protected function filterRolls(Request $request, $model)
    {
        $value = $request->input('value');
        if (empty($value)) {
            return $model;
        }
        $film = DB::table('film_type_master as ft');
        $film = filterByColumns($film, ['ft.english_value', 'ft.traditional_chiness_value', 'ft.simplified_chiness_value']);
        $film_ids = $film->get('ft.id');
        $model = $model->where(function ($query) use ($value, $film_ids) {
            $query->orWhereIn('rm.film_type_id', Arr::pluck($film_ids, 'id'))
                ->orWhere('rm.roll_number', 'like', '%'.$value.'%');
        });
        return $model;
    }

    public function show(Request $request, $id)
    {
        //checkAuthority();
        $user_id = session()->get('admin.id');
        $user_type = session()->get('admin.user_type');
        $page = [
            'page_name' => 'rolls',
            'title' => ts('VIEWROLLS'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEROLL'),
                    'url' => '/admin/rolls'
                ]
            ],
        ];
        $data = RollMaster::findOrFail($id);
        $transfer = @$data->transferRecords() ?: [];
        $wRecords = @$data->warrantyRecords() ?: [];
        $pRecords = @$data->precutRecords() ?: [];
        $rRecords = @$data->returnRecords() ?: [];
        $sRecords = @$data->salesRecords() ?: [];
        return view('admin.rolls.show', [
            'data'=>$data,
            'page' => $page,
            'wRecords' => $wRecords,
            'assigns' => $sRecords,
            'transfer' => $transfer,
            'pRecords' => $pRecords,
            'rRecords' => $rRecords,
        ]);

    }

    public function create(Request $request)
    {
        checkAuthority(1);
        $page = [
            'page_name' => 'rolls',
            'title' => ts('addROLL'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEROLL'),
                    'url' => '/admin/rolls'
                ]
            ],
        ];
        $data = new RollMaster();
        return view('admin.rolls.create', [
            'data'=>$data,
            'page' => $page,
        ]);
    }

    public function store(Request $request)
    {
        checkAuthority(1);
        $url = $request->input('_previous_') ?: '/admin/rolls';
        $roll_number = trim($request->input('roll_number'));
        $film_type_id = (int) $request->input('film_type_id');
        $length = (int) $request->input('length');
        if (empty($roll_number)) {
            return redirect()->back()->withInput()->with('trash', ['content'=>'卷号不能为空！', 'type'=>'error']);
        }
        if (empty($film_type_id)) {
            return redirect()->back()->withInput()->with('trash', ['content'=>'膜的种类不能为空！', 'type'=>'error']);
        }
        if (empty($length)) {
            return redirect()->back()->withInput()->with('trash', ['content'=>'膜长度不能为空！', 'type'=>'error']);
        }
        // 7788907
        $data = RollMaster::withTrashed()->where('roll_number', $roll_number)->first();
        if (!empty($data->id)) {
            if ($data->trashed()) {
                return redirect()->back()->withInput()->with('trash', ['content'=>$roll_number . ' 系统中已删除记录中存在相同卷号！', 'type'=>'error']);
            }
            return redirect()->back()->withInput()->with('trash', ['content'=>$roll_number . ' 系统中已存在相同卷号！', 'type'=>'error']);
        }
        DB::beginTransaction();
        try {
            $film = FilmTypeMaster::find($film_type_id);
            if (empty($film->id)) {
                DB::rollBack();
                return redirect()->back()->withInput()->with('trash', ['content'=>'膜的种类系统中不存在！', 'type'=>'error']);
            }
            $model = new RollMaster();
            $model->roll_number = $roll_number;
            $model->width = (int) $request->input('width');
            $model->film_type_id = $film_type_id;
            $model->length = $length;
            $model->status = 0;
            $model->product_type_id = (int) $film->product_type_id;
            $model->save();
            if (empty($model->roll_number)) {
                DB::rollBack();
                return redirect()->back()->withInput()->with('trash', ['content'=>'服务器错误，请稍后重试！', 'type'=>'error']);
            }
            $e = plusRestlen(1, $model->roll_number, $model->length);
            if (empty($e)) {
                DB::rollBack();
                return redirect()->back()->withInput()->with('trash', ['content'=>'服务器错误，请稍后重试！', 'type'=>'error']);
            }
            $alogs = alogs('膜卷', '添加', $model->id, $model, null);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return redirect()->back()->withInput()->with('trash', ['content'=>'服务器错误，请稍后重试！', 'type'=>'error']);
        }

        // uWMR($model); // 根据卷号更新卷号不存在信息

        $url = '/admin/rolls';
        session()->flash('hightlight', ['id'=>$model->id, 'type'=>'rolls']);
        return redirect($url)->with('trash', ts('ROLLADDSUCCESS'));
    }

    public function edit(Request $request, $id)
    {
        checkAuthority(1);
        $page = [
            'page_name' => 'rolls',
            'title' => ts('editROLL'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEROLL'),
                    'url' => '/admin/rolls'
                ]
            ],
        ];
        $data = RollMaster::select(['id', 'roll_number', 'film_type_id', 'length', 'width'])->findOrFail($id);
        $data->product_type_id = $data->getPID();
        return view('admin.rolls.edit', [
            'data'=>$data,
            'page' => $page,
        ]);
    }

    /*
     * 膜卷更新
     * 已删除的卷，无法修改
     * 已分配长度的卷，无法修改长度，不允许修改长度
     * 当管理员的剩余长度与卷长度不符合时，不允许修改长度
     * 长度修改后，自动更新管理员剩余长度*/
    public function update(Request $request, $id)
    {
        checkAuthority(1);
        $url = '/admin/rolls';
        $model = RollMaster::findOrFail($id);

        $alogs = alogs('膜卷', '修改', $model->id, null, $model);
        $model->width = (int) $request->input('width');
        $model->film_type_id = (int) $request->input('film_type_id');
        if (empty($model->film_type_id)) {
            return redirect()->back()->withInput()->with('trash', ['content'=> '模型号不能为空！', 'type'=>'error']);
        }
        $fm = FilmTypeMaster::find($model->film_type_id);
        if (empty($fm->id)) {
            return redirect()->back()->withInput()->with('trash', ['content'=> '模型号不存在，请确认！', 'type'=>'error']);
        }
        if (empty($model->width)) {
            return redirect()->back()->withInput()->with('trash', ['content'=> '膜宽度不能为空！', 'type'=>'error']);
        }
        // $length = (int) $request->input('length');
        $model->save();
        $alogs->new = $model;
        session()->flash('hightlight', ['id'=>$model->id, 'type'=>'rolls']);
        return redirect($url)->with('trash', ts('UPDATESUCCESS'));
    }

    public function destory(Request $request, $id)
    {
        return deleteRoll($id);
    }
    public function deletes(Request $request)
    {
        $ids = $request->input('id');
        if (empty($ids)) {
            return ['status'=>false, 'msg'=>'没有找到卷号'];
        }
        $count = 0;
        foreach ($ids as $k => $id) {
            $bool = deleteRoll($id);
            if (@$bool['status'] == 'SUCCESS') {
                $count += 1;
            }
        }
        return ['status' => 'SUCCESS', 'msg' => $count . ' 条数据删除成功，'. (count($ids) - $count) .'条数据删除失败！'];
    }

    /*
     * 卷膜分配
     * 当长度超过本身拥有的长度时，自动改为可分配长度*/
    public function assign(Request $request)
    {
        $admin_id = session('admin.id');
        $user_type = session('admin.user_type');
        if ($user_type == 1) {
            $admin_id = 1;
        } else if ($user_type != 2) {
            checkAuthority();
            $admin_id = 1;
        }
        $sold_by_user_id = $admin_id;
        $sold_to_user_id = (int) $request->input('user_id');
        $length = (int) $request->input('length');
        $all_length = (int) $request->input('all_length');
        $roll_number = trim($request->input('roll_id')); // 卷号
        if (empty($roll_number)) {
            return fs403('卷号不能为空！');
        }
        if (empty($length)) {
            return fs403('长度不能为空！');
        }
        if (empty($sold_to_user_id)) {
            return fs403('分配用户不能为空！');
        }

        DB::beginTransaction();
        try {
            $roll = RollMaster::where('roll_number', $roll_number)->first();
            if (empty($roll->id)) {
                return ['status' => false, 'msg' => '卷号不存在！'];
            }
            if ($roll->roll_number != $roll_number) {
                return fs500('服务器错误，请稍后重试！');
            }
            $rst = RollRestlen::where([
                'roll_number' => $roll->roll_number,
                'user_id' => 1,
            ])->first();
            if (empty($rst->id)) {
                plusRestlen(1, $roll->roll_number, $roll->length);
            }
            $restlen = getRlenV401($roll->roll_number, $admin_id);
            if ($all_length == 1) {
                $length = $restlen;
            }
            if ($length >= $restlen) {
                $length = $restlen;
            }

            $sid = addRollSales($roll->id, $sold_by_user_id, $sold_to_user_id, $length, 1);
            if (empty($sid)) {
                DB::rollback();//数据库回滚
                return fs500('分配失败，请刷新重试！');
            }
            $e = minusRestlen($sold_by_user_id, $roll->roll_number, $length);
            if (empty($e)) {
                DB::rollback();//数据库回滚
                return fs500('分配失败，请刷新重试！');
            }
            $e = plusRestlen($sold_to_user_id, $roll->roll_number, $length);
            if (empty($e)) {
                DB::rollback();//数据库回滚
                return fs500('分配失败，请刷新重试！');
            }
            if ($roll->status == 0) {
                $roll->status = 1;
                $roll->save();
            }
            DB::commit();
        } catch (\Exception $exception){
            DB::rollback();//数据库回滚
            return fs500('分配失败，请刷新重试！');
        }
        session()->flash('hightlight', ['id'=>$roll->id, 'type'=>'rolls']);
        return fs200('分配成功！', @$sid, $roll, $roll_number);
    }

    /*
     * 膜卷excel导入
     * 膜卷批量导入
     * 第一行为表头不录入*/
    public function import(Request $request)
    {
        checkAuthority();
        $page = [
            'page_name' => 'rolls',
            'title' => ts('bulkimport'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEROLL'),
                    'url' => '/admin/rolls'
                ]
            ],
        ];
        return view('admin.rolls.import', ['page'=>$page]);
    }

    /*
     * 第一行为表头不录入*/
    public function handle_import(Request $request)
    {
        checkAuthority();
        $page = [
            'page_name' => 'rolls',
            'title' => ts('bulkimport'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEROLL'),
                    'url' => '/admin/rolls'
                ]
            ],
        ];
        $user_id = session('admin.id');
        $file = $request->file('file');
        if (empty($file)) {
            return redirect()->back()->withInput()->with('trash', ['content'=>'文件不存在！', 'type'=>'error']);
        }
        if ($file->getClientOriginalExtension() != 'xlsx') {
            return redirect()->back()->withInput()->with('trash', ['content'=>'仅支持上传xlsx类型文件', 'type'=>'error']);
        }

        $filename = Str::random(16) . '.xlsx';
        $path = getFileStorePath(2);
        $bool = $file->storeAs($path['path'], $filename, 'storage');
        $full_file_name = $path['path'].$filename; // /upload/XXX/filename
        $mod = new FileUpload();
        $mod->type = 2;
        $mod->name = '膜卷文件上传';
        $mod->user_id = $user_id;
        $mod->file = $full_file_name;
        $mod->save();

        $spreadsheet = IOFactory::load($path['base'] . $filename);
        $arrays = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
        $time = date('Y-m-d H:i:s');
        $datas = [];
        foreach ($arrays as $k => $v) {
            if ($k == 1) {
                continue;
            }
            $datas[] = [
                'roll_number' => trim($v['A']),
                'film_type_id' => (int) $v['B'],
                'width' => (int) $v['C'],
                'length' => (int) $v['D'],
                'created_at' => $time,
                'updated_at' => $time,
            ];
        }
        $roll_number = Arr::pluck($datas, 'roll_number');
        $ed = DB::table('roll_master')->whereIn('roll_number', $roll_number)->get(['roll_number']);
        $ex = Arr::pluck($ed, 'roll_number');
        $uploads = [];
        $restlen = [];
        $filmType = FilmTypeMaster::get();
        $ftids = Arr::pluck($filmType, 'id');
        foreach ($datas as $k => $v) {
            if (empty($v['roll_number'])) {
                continue;
            }
            $state = true;
            if (in_array($v['roll_number'], $ex)) {
                $v['exist'] = true;
                $v['error_info'] = $v['roll_number'] . ' 系统中已存在相同卷号！';
                $state = false;
            }
            if (empty($v['film_type_id'])) {
                $v['error_info'] = @$v['error_info'] .' 模型号不能为空！';
                $state = false;
            } else if (!in_array($v['film_type_id'], $ftids)) {
                $v['error_info'] = @$v['error_info'] .' 模型号系统中不存在，请确认！';
                $state = false;
            }
            if ($v['length'] <= 0) {
                $v['error_info'] = @$v['error_info'] .' 模长度不能为空！';
                $state = false;
            }
            $datas[$k] = $v;
            if ($state) {
                DB::beginTransaction();
                try {
                    $model = new RollMaster();
                    $model->roll_number = $v['roll_number'];
                    $model->width = $v['width'];
                    $model->film_type_id = $v['film_type_id'];
                    $model->length = $v['length'];
                    $model->status = 0;
                    $model->save();
                    if (empty($model->id)) {
                        DB::rollback();//数据库回滚
                        $v['error_info'] = '服务器错误，保存失败！';
                        continue;
                    }
                    $e = plusRestlen(1, $model->roll_number, $model->length);
                    if (empty($e)) {
                        DB::rollback();//数据库回滚
                        $v['error_info'] = '服务器错误，保存失败！';
                        continue;
                    }
                    DB::commit();
                    $ex[] = $v['roll_number'];
                }  catch (\Exception $exception){
                    DB::rollback();//数据库回滚
                    $v['error_info'] = '服务器错误，保存失败！';
                }
            }
        }
        $alogs = alogs('膜卷', '导入', 0, $uploads, null);
        return view('admin.rolls.import-result', [
            'data'=>$datas,
            'page' => $page,
        ])->with('trash', '导入成功！');
    }

    /*
     * 膜卷excel导入
     * 膜卷批量导入
     * 第一行为表头不录入*/
    public function importDistribution(Request $request)
    {
        $page = [
            'page_name' => 'rolls',
            'title' => ts('BULKDISTIMPORT'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEROLL'),
                    'url' => '/admin/rolls_distribution'
                ]
            ],
        ];
        return view('admin.rolls.import_distribution', ['page'=>$page]);
    }

    public function handleImportDistribution(Request $request)
    {
        $page = [
            'page_name' => 'rolls',
            'title' => ts('bulkimport'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEROLL'),
                    'url' => '/admin/rolls'
                ]
            ],
        ];
        $admin_id = session('admin.id');
        $file = $request->file('file');
        if (empty($file)) {
            return redirect()->back()->withInput()->with('trash', ['content'=>'文件不存在！', 'type'=>'error']);
        }
        if ($file->getClientOriginalExtension() != 'xlsx') {
            return redirect()->back()->withInput()->with('trash', ['content'=>'仅支持上传xlsx类型文件', 'type'=>'error']);
        }
        $filename = Str::random(16) . '.xlsx';
        $path = getFileStorePath(2);
        $bool = $file->storeAs($path['path'], $filename, 'storage');
        $full_file_name = $path['path'].$filename; // /upload/XXX/filename
        $mod = new FileUpload();
        $mod->type = 2;
        $mod->name = '膜卷分配文件上传';
        $mod->user_id = $admin_id;
        $mod->file = $full_file_name;
        $mod->save();

        $spreadsheet = IOFactory::load($path['base'] . $filename);
        $datas = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
        $time = date('Y-m-d H:i:s');
        $userName = [];

        $user_type = session('admin.user_type');
        if ($user_type == 1) {
            $admin_id = 1;
        } else if ($user_type != 2) {
            checkAuthority();
            $admin_id = 1;
        }
        $sold_by_user_id = $admin_id;

        foreach($datas as $key => &$value) {
            if ($key == 1) {
                continue;
            }
            $rollNumber = trim($value['A']);
            $length = (int)$value['B'];
            $roll = RollMaster::where('roll_number', $rollNumber)->first();
            if (empty($roll->id)) {
                $value['error_info'] = '未查到对应的膜卷号，保存失败！';
                continue;
            }

            $rst = RollRestlen::where([
                'roll_number' => $rollNumber,
                'user_id' => 1,
            ])->first();
            if (empty($rst->id)) {
                plusRestlen(1, $rollNumber, $roll->length);
            }
            $restlen = getRlenV401($roll->roll_number, $admin_id);
            if (isset($all_length) && $all_length == 1) {
                $length = $restlen;
            }
            if ($length > $restlen) {
                $value['error_info'] = '可分配膜长度不足';
                continue;
            }
            if ($length <= 0) {
                $value['error_info'] = '可分配膜长度不足';
                continue;
            }

            $userName = [trim($value['C']), trim($value['D'])];
            $users = Users::whereIn('abbr', $userName)->select('id', 'creator_id', 'abbr', 'user_type', 'status', 'deleted_at')->get();
            if (empty($users)) {
                $value['error_info'] = '用户信息未查询到，保存失败！';
                continue;
            }

            $soldUser = [];
            $distributors = [];
            foreach ($users as $user) {
                if (!empty($user['deleted_at']) && $user['user_type'] == 2) {
                    $value['error_info'] = '省代被禁用，保存失败！';
                    continue;
                }
                if (!empty($user['deleted_at']) && $user['user_type'] == 3) {
                    $value['error_info'] = '经销商被禁用，保存失败！';
                    continue;
                }
                if (strcmp($user['status'], '0') === 0 && $user['user_type'] == 2) {
                    $value['error_info'] = '省代被停用，保存失败！';
                    continue;
                }
                if ($user['abbr'] == trim($value['C'])) {
                    $distributors = $user;
                }
                if ($user['abbr'] === trim($value['D'])) {
                    $soldUser = $user;
                }
            }

            if (empty($distributors)) {
                $value['error_info'] = '经销商信息未查询到，保存失败！';
                continue;
            }

            if ($user_type == 2 && $distributors['id'] != $admin_id) {
                $value['error_info'] = '经销商不可分配其他经销商数据，保存失败！';
                continue;
            }

            if ($user_type == 2 && $soldUser['id'] == $admin_id) {
                $value['error_info'] = '经销商不可分配给自己，保存失败！';
                continue;
            }

            if (empty($soldUser)) {
                $value['error_info'] = '待分配用户信息未查询到，保存失败！';
                continue;
            }

            if ($soldUser['id'] != $distributors['id'] && $soldUser['creator_id'] != $distributors['id']) {
                $value['error_info'] = '待分配用户和省代关系有误，保存失败！';
                continue;
            }
            DB::beginTransaction();
            try {
                $sid = addRollSales($roll->id, $sold_by_user_id, $soldUser['id'], $length, 1);
                if (empty($sid)) {
                    $value['error_info'] = '分配失败-1！';
                    DB::rollBack();
                    continue;
                }
                $e = minusRestlen($sold_by_user_id, $roll->roll_number, $length);
                if (empty($e)) {
                    $value['error_info'] = '分配失败-2！';
                    DB::rollBack();
                    continue;
                }
                $e = plusRestlen($soldUser['id'], $roll->roll_number, $length);
                if (empty($e)) {
                    $value['error_info'] = '分配失败-3！';
                    DB::rollBack();
                    continue;
                }
                if ($roll->status == 0) {
                    $roll->status = 1;
                    $roll->save();
                }
                DB::commit();
            } catch (\Exception $exception) {
                DB::rollback();//数据库回滚
                $value['error_info'] = '分配失败-4！';
            }
        }

        $alogs = alogs('膜卷', '导入', 0, [], null);
        return view('admin.rolls.import_distribution_result', [
            'data' => $datas,
            'page' => $page,
        ])->with('trash', '导入成功！');
    }

    public function getRollsType(Request $request)
    {
        $locale = App::getLocale();
        $user_id = session('admin.id');
        $user_type = session('admin.user_type');
        if (empty($request->input('product_id'))) {
            return [];
        }
        if ($locale == 'zh_tw') {
            $select = 'traditional_chiness_value as value';
        } elseif ($locale === 'en') {
            $select = 'english_value as value';
        } else {
            $select = 'simplified_chiness_value as value';
        }

        $userIds = [];
        $userService = new UserService();
        if ($user_type == 2) {
            $userIds = array_merge([$user_id], $userService->getDealers([$user_id]));
        } elseif ($user_type == 4) {
            $userIds = array_merge([$user_id], $userService->getDistributions(4, $user_id));
            $userIds = array_merge($userIds, $userService->getDealers($distributors ?? []));
        }
        if (in_array($user_type, [2, 4])) {
            $data = DB::table('film_type_master')
                ->whereIn('id', function ($query) use ($userIds, $request) {
                    $query->select('film_type_id')
                        ->from('roll_master as rm')
                        ->leftJoin('roll_restlen as rr', 'rr.roll_number', 'rm.roll_number')
                        ->whereIn('rr.user_id', $userIds)
                        ->where('rm.product_type_id', $request->input('product_id'))
                        ->groupBy('film_type_id');
                })
                ->select('id', $select)
                ->get();
            return $data;
        }
        return [];
    }
    /*
     * 整理EXCEL数据*/

    /*
     * 数据导出*/
    public function export(Request $request)
    {
        // $user_id = session()->get('admin.id');
        // $user_type = session()->get('admin.user_type');
        $m = $request->input('m');
        $model = DB::table('roll_master as rm')
            ->leftJoin('roll_restlen as rr', 'rm.roll_number', 'rr.roll_number')
            ->leftJoin('roll_sales as rs', 'rm.id', 'rs.roll_id')
            ->whereNull('rr.deleted_at')
            ->select([
                'rm.*',
                'rr.restlen',
                'rs.created_at as rs_create_at'
            ]);
//        if ($m == 1) {
//            $model = $model->where('rm.status', 1);
//        }
        $status = $request->input('status');
        if ($status !== null) {
            $model = $model->where('rm.status', $status);
        }
        $model = filterByDateRange($model, 'rm.created_at');
        $product_type_id = (int) $request->input('product_type_id');
        $film_type_id = (int) $request->input('film_type_id');
        if (!empty($film_type_id)) {
            $model = $model->where('rm.film_type_id', $film_type_id);
        } else if (!empty($product_type_id)) {
            $model = $model->leftJoin('film_type_master as ftmm', 'rm.film_type_id', 'ftmm.id')
                ->where('ftmm.product_type_id', $product_type_id);
        }
        $distributor_id = (int) $request->input('distributor_id');
        $dealer_id = (int) $request->input('dealer_id');
        if (!empty($dealer_id)) {
            $model = $model->leftJoin('warranty_to_vehicle_coverage as wvc', 'rm.roll_number', 'wvc.roll_number')
                ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
                ->leftJoin('precut_to_vehicle_coverage as pvc', 'rm.roll_number', 'pvc.roll_number')
                ->leftJoin('precut as p', 'p.id', 'pvc.precut_kit_sale_id')
                ->where(function ($query) use ($dealer_id) {
                    $query->where(function ($q2) use ($dealer_id) {
                        $q2->where('rr.user_id', $dealer_id)
                            ->where('rr.restlen', '>', 0);
                    })
                        ->orWhere(function ($query) use ($dealer_id) {
                            $query->where('w.user_id', $dealer_id)
                                ->where('w.approved', 1)
                                ->whereNotNull('wvc.warranty_id')
                                ->whereNull('w.deleted_at')
                                ->whereNull('wvc.deleted_at');
                        })
                        ->orWhere(function ($query) use ($dealer_id) {
                            $query->where('p.created_by', $dealer_id)
                                ->whereNotNull('p.id')
                                ->whereNull('p.deleted_at')
                                ->whereNull('pvc.deleted_at');
                        });
                });
        } else if (!empty($distributor_id)) {
            $model = $model->leftJoin('warranty_to_vehicle_coverage as wvc', 'rm.roll_number', 'wvc.roll_number')
                ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
                ->leftJoin('precut_to_vehicle_coverage as pvc', 'rm.roll_number', 'pvc.roll_number')
                ->leftJoin('precut as p', 'p.id', 'pvc.precut_kit_sale_id')
                ->where(function ($query) use ($distributor_id) {
                    $query->where(function ($q2) use ($distributor_id) {
                        $q2->whereIn('rr.user_id', function ($query) use ($distributor_id) {
                            $query->select('id')
                                ->from('users')
                                ->where('id', $distributor_id)
                                ->orWhere('creator_id', $distributor_id);
                        })
                            ->where('rr.restlen', '>', 0);
                    })
                        ->orWhere(function ($query) use ($distributor_id) {
                            $query->whereIn('w.user_id', function ($query) use ($distributor_id) {
                                $query->select('id')
                                    ->from('users')
                                    ->where('id', $distributor_id)
                                    ->orWhere('creator_id', $distributor_id);
                            })
                                ->whereNotNull('wvc.warranty_id')
                                ->whereNull('w.deleted_at')
                                ->whereNull('wvc.deleted_at');
                        })

                        ->orWhere(function ($query) use ($distributor_id) {
                            $query->whereIn('p.created_by', function ($query) use ($distributor_id) {
                                $query->select('id')
                                    ->from('users')
                                    ->where('id', $distributor_id)
                                    ->orWhere('creator_id', $distributor_id);
                            })
                                ->whereNotNull('p.id')
                                ->whereNull('p.deleted_at')
                                ->whereNull('pvc.deleted_at');
                        });
                });
        }
//        if (!empty($distributor_id)) {
//            $model = $model->leftJoin('warranty_to_vehicle_coverage as wvc', 'rm.roll_number', 'wvc.roll_number')
//                ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
//                ->leftJoin('precut_to_vehicle_coverage as pvc', 'rm.roll_number', 'pvc.roll_number')
//                ->leftJoin('precut as p', 'p.id', 'pvc.precut_kit_sale_id')
//                ->where(function ($query) use ($distributor_id) {
//                    $query->where(function ($q2) use ($distributor_id) {
//                        $q2->whereIn('rr.user_id', function ($query) use ($distributor_id) {
//                            $query->select('id')
//                                ->from('users')
//                                ->where('id', $distributor_id)
//                                ->orWhere('creator_id', $distributor_id);
//                        })
//                            ->where('rr.restlen', '>', 0);
//                    })
//                        ->orWhere(function ($query) use ($distributor_id) {
//                            $query->whereIn('w.user_id', function ($query) use ($distributor_id) {
//                                $query->select('id')
//                                    ->from('users')
//                                    ->where('id', $distributor_id)
//                                    ->orWhere('creator_id', $distributor_id);
//                            })
//                                ->whereNotNull('wvc.warranty_id')
//                                ->whereNull('w.deleted_at')
//                                ->whereNull('wvc.deleted_at');
//                        })
//
//                        ->orWhere(function ($query) use ($distributor_id) {
//                            $query->whereIn('p.created_by', function ($query) use ($distributor_id) {
//                                $query->select('id')
//                                    ->from('users')
//                                    ->where('id', $distributor_id)
//                                    ->orWhere('creator_id', $distributor_id);
//                            })
//                                ->whereNotNull('p.id')
//                                ->whereNull('p.deleted_at')
//                                ->whereNull('pvc.deleted_at');
//                        });
//                });
//        }
//        $dealer_id = (int) $request->input('dealer_id');
//        if (!empty($dealer_id)) {
//            $model = $model->where('rs.sold_to_user_id', $dealer_id);
//        }
        $model = $this->filterRolls($request, $model);
        $data = $model->orderByDesc('rm.id')
            ->groupBy('rm.id')
            ->limit(3000)
            ->get();
        $uploads = [];
        //序号,膜卷号,膜的种类,膜长度,剩余可分配长度,状态,销售时间
        $fields = [
            'number' => '序号',
            'roll_number' => '膜卷号',
            'film_type_id'   => '膜的种类',
            'length' => '膜长度',
            'restlen' => '剩余可分配长度',
            'status' => '状态',
            'rs_create_at' => '销售时间'
        ];
        $n=1;
        foreach ($data as $k => $v) {
            $v->number =$n;
            $v->film_type_id = ts('film_type_master.'.$v->film_type_id);
            $v->length = $v->length."cm";
            $v->restlen = $v->restlen."cm";
            $v->status = ts('RMST'.$v->status);
            $v->rs_create_at = !empty($v->rs_create_at) ? fdate2($v->rs_create_at) : '-';
            $item = [];
            foreach ($fields as $f => $m) {
                $item[] = [
                    'label' => $m,
                    'value' => $v->$f
                ];
            }
            $uploads[] = $item;
            $n++;
        }
        return makeExcel($uploads, '膜管理');
    }
}
